package game.script;

import hscript.Parser;

class ScriptTools {
	/**
	 * 将{}括号内的内容输出
	 * @param source 
	 * @return String
	 */
	public static function outBlock(source:String, start = "{", end = "}"):String {
		var codes = source.split(start);
		codes.shift();
		source = codes.join(start);
		codes = source.split(end);
		codes.pop();
		source = codes.join(end);
		return source;
	}

	/**
	 * 读取Var变量名称
	 * @param source 
	 * @return String
	 */
	public static function readVarName(source:String):String {
		var codes = source.split(" ");
		var read = false;
		var name = "";
		for (code in codes) {
			if (code == "var") {
				read = true;
			} else if (read && code != "") {
				name = code;
				break;
			}
		}
		return name.split(":")[0];
	}

	/**
	 * 读取Var变量数据
	 * @param source 
	 * @return Dynamic
	 */
	public static function readVarData(source:String, script:Script):Dynamic {
		if (source.indexOf("=") != -1) {
			var codes = source.split("=");
			var hscript:Parser = new Parser();
			hscript.allowTypes = true;
			hscript.allowJSON = true;
			hscript.allowMetadata = true;
			var expr = hscript.parseString("return " + codes[1]);
			return script.execute(expr);
		}
		return null;
	}

	/**
	 * 将所有super的方法调用删除
	 * @param source 
	 * @return String
	 */
	public static function removeSuperCode(source:String):String {
		var req = ~/super\.\w+\(.*\);/g;
		source = req.replace(source, "");
		return source;
	}

	/**
	 * 读取方法参数
	 * @param source 
	 * @return Array<String>
	 */
	public static function readArgs(source:String):Array<String> {
		var codes = source.split("{");
		var code = codes.shift();
		var req = ~/\(.+\)/g;
		var args = [];
		if (req.match(code)) {
			var argsString = outBlock(req.matched(0), "(", ")");
			var argsList = argsString.split(",");
			for (s in argsList) {
				if (s.indexOf(":") != -1) {
					var paramsName = s.split(":")[0];
					args.push(paramsName);
				} else {
					args.push(s);
				}
			}
		}
		return args;
	}
}
